package user_mgt

import (
	"context"
	"fmt"
	"net/http"
	"time"
)

// 从Cookies中获取token
func getTokenByCookies(cookies []*http.Cookie) (string, error) {
	// 检查logger是否为空
	if logger == nil {
		fmt.Println("logger is nil")
		return "", fmt.Errorf("logger is nil")
	}
	logger.Info("---->user_mgt/internal/auth.checkCookieHaveSessionId is run")

	//遍历cookies
	for _, cookie := range cookies {
		//检查cookie是否为空
		if cookie == nil {
			logger.Errorf("cookie is nil")
			return "", fmt.Errorf("cookie is nil")
		}
		//检查cookie.Name是否为token
		if cookie.Name == "token" {
			return cookie.Value, nil
		}
	}

	//在cookies中没有找到token字段
	return "", nil
}

// 将键值对传入上下文
func setToContext(key string, value string, ctx context.Context) (context.Context, error) {
	// 检查key是否为空
	if key == "" {
		logger.Errorf("key is empty")
		return ctx, fmt.Errorf("key is empty")
	}

	// 检查value是否为空
	if value == "" {
		logger.Errorf("value is empty")
		return ctx, fmt.Errorf("value is empty")
	}

	// 将key-value存入context
	ctx = context.WithValue(ctx, key, value)

	return ctx, nil
}

// 将 token 写入到 Cookies 的 token 字段
func setTokenToCookies(w http.ResponseWriter, token string) {
	// 创建一个新的 Cookie
	cookie := &http.Cookie{
		Name:     "token",
		Value:    token,
		Path:     "/",
		Expires:  time.Now().Add(2 * 24 * time.Hour),
		MaxAge:   172800,
		Secure:   false,
		HttpOnly: false,
		SameSite: http.SameSiteLaxMode,
	}

	// 将 Cookie 写入 LoginResponse Header
	http.SetCookie(w, cookie)

	logger.Info("Token set to cookies successfully")
}
